<?php

namespace app\scm\controller;

use app\admin\common\Base;
use think\Db;
use think\Session;
use app\admin\common\Excel;

use app\scm\model\OrderInvup as OrderinvupModel;

class Orderinvupreport extends Base
{
    public function index()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);
            if (isset($data['startdate']) && isset($data['enddate'])) {
                $month = $this->get_month_start_to_end($data['startdate'], $data['enddate']);
            } else {
                $month = $this->get_month_start_to_end();
            }

          
            $sql = Db::name('order_good')->alias('a')->join('order b', 'a.order_id = b.id')->field('a.good_id, a.order_id, a.shuliang, a.unit_id, a.store_id, a.price, a.addtime, a.total_price, b.*,a.id as a_id,b.id as b_id')->where('b.addtime', '>=', $month['month_start'])->where('b.addtime', '<=', $month['month_end'])->where(['b.is_del' => 0, 'b.enterprise_id' => $this->EnterpriseId]);
            $sql = $sql->where('b.o_type', 3)->where('a.type', 3);
            //search
            $sql = !isset($data['supplierid'])||$data['supplierid'] == '' ? $sql : $sql->where('b.user_id','in', $data['supplierid']);
            $sql = !isset($data['supplierid'])||$data['goodsid'] == '' ? $sql : $sql->where('a.good_id','in', $data['goodsid']);
            $sql = empty($data['sn']) ? $sql : $sql->where('b.sn', 'like', '%' . trim($data['sn']) . '%');
            // 高级搜索
            extract($data);
          
            $sql = empty($jh_time_start) ? $sql : $sql->where('b.jh_time', '>=', strtotime($jh_time_start));
            $sql = empty($jh_time_end) ? $sql : $sql->where('b.jh_time', '<=', strtotime($jh_time_end));

            $arrStatus = empty($status) ? []: explode(',', $status);
            if ($arrStatus) {
                $a_status = [];
                array_walk($arrStatus, function ($v) use ($sql, &$a_status) {
                    switch ($v) {
                        case 1:
                            $a_status[] = 0;
                            break;
                        case 3:
                            $a_status[] = 1;
                            break;
                        case 4:
                            $sql = $sql->where('b.is_close', 1);
                            break;
                        case 5:
                            $sql = $sql->order('a.good_id');
                            break;
                        case 6:
                            $sql = $sql->order('b.sn');
                            break;
                        default:
                            # code...
                            break;
                    }
                });
                $sql = empty($a_status) ? $sql : $sql->where('b.status', 'in', $a_status);
            }
            // 供应商类别
            if (!isset($data['supplier_category_id']) || $data['supplier_category_id'] == 0 || $data['supplier_category_id'] == '') {
            } else {
                $c = Db::name('customer')->where('category_id', $data['supplier_category_id'])->select();
                $c['ids'] = implode(',', array_column($c, 'id'));
                $sql->where('b.user_id',  $c['ids']); //商品类别
            }
            $arr = $sql->order('good_id asc,updatetime desc')->select();
            //$arr = $sql->fetchSql(true)->select();
           
            
            foreach ($arr as $key => &$value) {
                $list1=[];
                $og=$this->order_good_one($value['a_id']);
                $o=$this->order_one($value['order_id']);
                foreach ($og as $ke=> $va) {
                    $list1[$ke]=$va;
                }
                foreach ($o as $k=> $v) {
                   if (!isset($list1[$k])) {
                      $list1[$k]=$v;
                   }
                }
                $value=$list1;
            }
            if(isset($data['is_export']) && $data['is_export'] == 1){//如果是导出操作
                return $this->export($arr);
            }
            $count = count($arr);
            $list = array_slice($arr, $start, $limit);
            return $this->grid_data($list, $count, $page, $limit);
        }
        $customer = Db::name('customer')->where('is_customer', 'in', '1,3')->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        $goods = Db::name('goods')->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();

        $this->assign('customer', $customer);
        $this->assign('goods', $goods);
        return $this->fetch();
    }

     public function export($volist){
        $arr_list=[];
        if(!empty($volist)){
            foreach ($volist as $key => $val) {
                array_push($arr_list, $val);
                // $og_list = Db::name('order_good')->where('order_id',$val['id'])->where('is_del',0)->select();
                // foreach ($og_list as $k => $v) {
                //     $arr=$val;
                //     $og=$this->order_good_one($v['id']);
                //     //halt($og);
                //     foreach ($og as $k1 => $v1) {
                //        $arr[$k1]=$v1;
                //     }
                //     array_push($arr_list, $arr);
                // }
               
                // $hj_arr=$title;
                // foreach ($hj_arr as $ke => $va) {
                //     $hj_arr[$ke]='';
                // }
                // $hj_arr['sn']=$val['sn'];
                // $hj_arr['good_sn']="合计";

                // $hj_arr['shuliang']= array_sum(array_map(function($value){return $value['shuliang'];}, $og_list));//求二维数组某一项的和
                // $hj_arr['zk_e']= array_sum(array_map(function($value){return $value['zk_e'];}, $og_list));//求二维数组某一项的和
                // $hj_arr['jine']= array_sum(array_map(function($value){return $value['jine'];}, $og_list));//求二维数组某一项的和
                // $hj_arr['tax_e']= array_sum(array_map(function($value){return $value['tax_e'];}, $og_list));//求二维数组某一项的和
                // $hj_arr['total_price']= array_sum(array_map(function($value){return $value['total_price'];}, $og_list));//求二维数组某一项的和
                // array_push($arr_list, $hj_arr);
            }  
        }
        $excel = new Excel();
        $title = [
            'good_sn' => '商品编号',
            'good_name' => '商品名称',
            'good_model' => '规格型号',
            'unit_name' => '单位',
            'dj_time' => '订单日期',
            'sn'=>"采购订单编号",
            'customer_name'=>'供应商',
            'store_name'=>'仓库',
            'order_status'=>'状态',  
            'shuliang'=>'数量', 
            'hs_price'=>'单价', 
            'total_price'=>'采购额', 
            'w_ruku_shuliang'=>'未入库数量', 
            'w_ruku_jine'=>'未入库金额', 
            'jh_time'=>'预计交货日期', 
            'last_ruku_time'=>'最后入库日期', 
            'mark'=>'备注',
        ]; 
        $arr_list=[];
        if(!empty($volist)){
           $arr_list=$volist;
        }

        //添加标题到数组头部
        array_unshift($arr_list,$title);
        $kong_arr=$title;
        foreach ($kong_arr as $ke1 => $va1) {
            $kong_arr[$ke1]='';
        }
        for ($i=0; $i <3 ; $i++) { 
            array_unshift($arr_list,$kong_arr);
        }
        //根据此参数获取数据中的值，要与表格标题键名对应
        $keys=[];
        foreach ($title as $k2 => $v2) {
            array_push($keys, $k2);
        }

        $merge=[];
        $options=[
            'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q'],//居中
            'bold'=>['A1:Q3','A4:Q4'],//加粗
            'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
        ];
        $title=[//标题
            'title'=>"采购订单跟踪表",
            'max_zimu'=>"Q",
            'number'=>'3',
        ];
        $excel_export_title="采购订单跟踪表_" . date('Y-m-d_His') . '.xlsx';//文件名称
        $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,-1,$merge,$title);
        exit();
    }


    public function add()
    {
        $supplier = Db::name('supplier')->where('is_del', 0)->select();
        $this->assign('supplier', $supplier);
        return $this->fetch();
    }

    //编辑栏目1-1
    public function edit($id)
    {
        $info = Db::name('supplier')->where('id', $id)->find();
        $info['addtime'] = date('Y-m-d', $info['addtime']);

        $supplier = Db::name('supplier')->where('is_del', 0)->select();
        $this->assign('supplier', $supplier);
        $this->assign('info', $info);
        return $this->fetch();
    }
    //编辑栏目1-2
    public function save()
    {
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();
        $basedata = $data['basedata'];
        $extdata = $data['extdata'];
        $model = new OrderinvupModel();
        // 启动事务
        Db::startTrans();
        if (empty($basedata['id'])) {
            $basedata['enterprise_id'] = $this->EnterpriseId;
            $basedata['addtime'] = strtotime($basedata['addtime']);
            $basedata['delivery_time'] = strtotime($basedata['delivery_time']);
            $result = $model->allowField(true)->save($basedata);
            if (!$result) {
                // 回滚事务
                Db::rollback();
                return ['status' => $status, 'msg' => $msg];
            }
            $lastid = Db::name('order_invpu')->where(['enterprise_id' => $this->EnterpriseId, 'is_del' => 0])->getLastInsID();
            // 新增客户扩展信息
            foreach ($extdata as $key => &$value) {
                if (!empty($value['goods_id'])) {

                    $value['order_invpu_id'] = $lastid;
                    $value['enterprise_id'] = $this->EnterpriseId;
                }
            }

            if (!empty($extdata)) {
                $sub = Db::name('order_invpu_goods')->insertAll($extdata);
                if (!$sub) {
                    // 回滚事务
                    Db::rollback();
                    return ['status' => $status, 'msg' => $msg];
                }
            }

            // 提交事务
            Db::commit();
            $status = 1;
            $msg = "添加成功";
        } else {
            $id = $basedata['id'];
            $basedata['addtime'] = strtotime($basedata['addtime']);
            $basedata['delivery_time'] = strtotime($basedata['delivery_time']);
            $result = $model->allowField(true)->save($basedata, ["id" => $id]);
            if ($result === false) {
                // 回滚事务
                Db::rollback();
                return ['status' => $status, 'msg' => $msg];
            }
            // 删除所有扩展信息
            $ext_info = Db::name('order_invpu_goods')->where(['order_invpu_id' => $id, 'is_del' => 0])->count();
            if ($ext_info > 0) {
                $del_ext = Db::name('order_invpu_goods')->where('order_invpu_id', $id)->update(["is_del" => 1]);
                if ($del_ext === false) {
                    // 回滚事务
                    Db::rollback();
                    return ['status' => $status, 'msg' => $msg];
                }
            }
            // 新增客户扩展信息
            foreach ($extdata as $key => &$value) {
                if (!empty($value['goods_id'])) {

                    $value['order_invpu_id'] = $id;
                    $value['enterprise_id'] = $this->EnterpriseId;
                }
            }

            if (!empty($extdata)) {
                $sub = Db::name('order_invpu_goods')->insertAll($extdata);
                if (!$sub) {
                    // 回滚事务
                    Db::rollback();
                    return ['status' => $status, 'msg' => $msg];
                }
            }

            // 提交事务
            Db::commit();
            $status = 1;
            $msg = "更新成功";
        }
        return ['status' => $status, 'msg' => $msg];
    }

    // 获取用户扩展信息
    public function getExtInfo($id)
    {
        $ext_info = Db::name('order_invpu_goods')->where(['order_invpu_id' => $id, 'is_del' => 0])->select();
        return json($ext_info);
    }

    //删除栏目1-1
    public function del($id)
    {
        $status = 0;
        $msg = "操作失败";
        $del = Db::name('order_invpu')->where('id', $id)->update(["is_del" => 1]);
        if ($del) {
            // 删除客户扩展信息
            Db::name('order_invpu_goods')->where('order_invpu_id', $id)->update(["is_del" => 1]);

            $status = 1;
            $msg = "删除成功";
        }
        return ['status' => $status, 'msg' => $msg];
    }

    // 状态
    public function status()
    {
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();
        $model = new OrderinvupModel();
        $id = $data['id'];
        $result = $model->allowField(true)->save($data, ["id" => $id]);
        if ($result) {
            $status = 1;
            $msg = "更新成功";
        }
        return ['status' => $status, 'msg' => $msg];
    }
}
